/*
 * @Author: Leo Zhang（张吉军）
 * @Description:
 * @需求文档：
 * 高保真：
 * API：
 */

import React, { useEffect, useState } from 'react';
import { Link, Outlet } from 'react-router-dom';
import { Input, Select, Carousel, Card, Spin } from 'antd';
import { useNavigate, useSearchParams, useLocation } from 'react-router-dom';
import moment from 'moment';
import baseService from '@service/baseService';
import logoUrl from '@assets/logo.jpg';
import testUrl from '@assets/test.png';
import schoolUrl from '@assets/school1.jpg';
import closeUrl from '@assets/close.png';
import styles from './style.module.less';
import app from "../../constant/index";

const { Search } = Input;

const handlePathstr = (path) => {
  return path?.replace(
    'https://edu-platform-file.oss-cn-hangzhou.aliyuncs.com',
    '/mine'
  );
};

const Home = (props) => {
  const radmonTime = new Date().getTime();
  const location = useLocation();
  let [searchParams, setSearchParams] = useSearchParams();
  const [activeSubjectId, setActiveSubjectId] = useState(-1);
  const navigate = useNavigate();
  const [courseList, setCourseList] = useState([]);
  const [searchTxt, setSearchTxt] = useState('');
  const [searchPageList, setSearchPageList] = useState([]);
  const [pageLoading, setPageLoading] = useState(false);
  const [showModal, setShowModal] = useState(false); // 是否展示首屏广告弹窗
  const [sHowAnimal, setSHowAnimal] = useState();
  const isFirstShow = sessionStorage.getItem('isFirstOpen');

  useEffect(() => {
    setTimeout(() => {
      setSHowAnimal(true);
    }, 500);

    if(isFirstShow != null) {
      document.body.style.overflow = '';
      return;
    }
    document.body.style.overflow = showModal ? 'hidden' : '';;
    sessionStorage.setItem('isFirstOpen', 'first');
  }, []);

  useEffect(() => {
    setActiveSubjectId(searchParams.get('idx') || -1)
  }, [searchParams.get('idx')]);
  
  useEffect(() => {
    if(location?.state?.item?.subjectId) {
      setActiveSubjectId(location?.state?.item?.subjectId)
    }
  }, [location?.state]);

  useEffect(() => {
    document.body.style.overflow = showModal ? 'hidden' : '';
  }, [showModal]);

  useEffect(() => {
    console.log('home-[]-')

    // 获取头部科目列表
    handleSubjectList();

  }, []);

  const handleSubjectList = async () => {
    try {
      baseService.get('/edu/subject/list').then((res) => {
        if (res.code == 0) {
          setCourseList(res.data);
        }
      });
    } catch (error) {
      console.log('jj-error', error);
    }
  };

  const getAllSubjectList = () => {
    try {
      setPageLoading(true);
      baseService
        .get(`/edu/subject/file/list`)
        .then((res) => {
          if (res.code == 0) {
            setAllSubjectInfo(res?.data);
          }
        })
        .finally(() => {
          setPageLoading(false);
        });
    } catch (error) {}
  };
  const getHotSubjectInfo = () => {
    try {
      baseService.get(`/edu/subject/file/page?isHot=1`).then((res) => {
        if (res.code == 0) {
          setHotModule(res?.data?.list);
        }
      });
    } catch (error) {}
  };
  const handleTabClick = (nav, idx) => {
    setActiveSubjectId(nav.id);
    if (nav.name == '首页') {
      navigate('/subjectRecommad');
      return;
    }
    navigate(`/subjectList?name=${nav.name}&idx=${idx}`);
  };

  const onChange = (e) => {
    setSearchTxt(e?.target?.value);
  };

  const onSearch = () => {
    navigate('/searchPage', { state: { keyWord: searchTxt } });
  };

  const viewDetail = (item) => {
    const videoUrl = `${handlePathstr(item?.fileUrl)}`;
    try {
      baseService.put(`/edu/subject/file/2/${item.id}/count`)
    } catch (error) {
      
    }
    navigate('/acticleDetail', { state: { item, videoUrl } });
  };

  const closeModal = () => {
    setShowModal(false);
    document.body.style.overflow = '';
    sessionStorage.setItem('isFirstOpen', 'more');
  };

  const closeLayer = () => {
    setHideBabyModal(true);
    setTimeout(() => {
      closeBabyModal(false);
    }, 300);
  };

  const preventCloseLayer = (event) => {
    event.stopPropagation();
    event.cancelBubble = true;
  };
  return (
    <>
      <div className={styles.wrapper}>
        <div className={styles.searchBar}>
          {/* <img src={logoUrl} alt="" className={styles.logo} /> */}
          <span className={styles.name}>{app.name}</span>
          <Search
            placeholder="请输入关键字"
            enterButton="搜索"
            size="large"
            onSearch={onSearch}
            className={styles.searchInput}
            onChange={onChange}
            style={{ width: '600px', marginLeft: '100px' }}
          />
        </div>
        <div className={styles.navWrapper}>
          <div className={styles.narMenu}>
            {[{ id: -1, name: '首页' }, ...courseList]?.map((nav, idx) => {
              return (
                <div
                  onClick={() => handleTabClick(nav, idx)}
                  key={idx}
                  className={`${styles.narItem} ${
                    nav.id == activeSubjectId ? styles.narItemActive : ''
                  }`}
                >
                  {nav.name}
                </div>
              );
            })}
          </div>
        </div>

        {searchPageList?.length < 1 ? (
          <Outlet />
        ) : (
          <div className={styles.searchSourceList}>
            {searchPageList?.map((sub, idx) => {
              return (
                <div className={styles.record} onClick={() => viewDetail(sub)}>
                  <img src={testUrl} className={styles.testIcon} />
                  <span className={styles.testTxt}>{sub.title}</span>
                  <span className={styles.time}>
                    [{moment(sub.createDate).format('YYYY-MM-DD')}]
                  </span>
                </div>
              );
            })}
          </div>
        )}

        <div className={styles.footer_bg}>
          {/* <img src={logoUrl} alt="" className={styles.logo} /> */}
          <section className={styles.footer_section}>
            <p>{app.name} ©2024 版权所有 备案号：< a href="https://beian.miit.gov.cn" target="_blank">苏ICP备2024130913号</a ></p>
          </section>
        </div>

        <Spin size="large" spinning={pageLoading} fullscreen />
        {/* 
      {showModal && (
        <div className="content">
          <img src={closeUrl} className="closeIcon" onClick={closeModal} />
          <div className="grid">
            <div className="grid__item">
              <div
                className="tooltip tooltip--amras"
                data-type="amras"
                style={{ opacity: 1 }}
              >
                <div
                  className="tooltip__trigger"
                  role="tooltip"
                  aria-describedby="info-amras"
                />
                <div className="tooltip__base">
                  <svg
                    className="tooltip__shape"
                    width="100%"
                    height="100%"
                    viewBox="0 0 400 300"
                  >
                    <path
                      className="path-amras-2"
                      d="M 293,106 A 90.1,90.1 0 0 1 203,197 90.1,90.1 0 0 1 112,106 90.1,90.1 0 0 1 203,16.2 90.1,90.1 0 0 1 293,106 Z"
                    />
                    <path
                      className="path-amras-3"
                      d="M 324,66.2 A 46.9,46.9 0 0 1 277,113 46.9,46.9 0 0 1 230,66.2 46.9,46.9 0 0 1 277,19.3 46.9,46.9 0 0 1 324,66.2 Z"
                    />
                    <path
                      className="path-amras-1"
                      d="M 180,111 A 67.2,67.2 0 0 1 112,178 67.2,67.2 0 0 1 45.9,111 67.2,67.2 0 0 1 112,43.5 67.2,67.2 0 0 1 180,111 Z"
                    />
                    <path
                      className="path-amras-4"
                      d="M 371,98.6 A 52.7,52.7 0 0 1 318,152 52.7,52.7 0 0 1 266,98.6 52.7,52.7 0 0 1 318,45.9 52.7,52.7 0 0 1 371,98.6 Z"
                    />
                    <path
                      className="path-amras-9"
                      d="M 375,167 A 66.8,55.1 0 0 1 308,222 66.8,55.1 0 0 1 241,167 66.8,55.1 0 0 1 308,112 66.8,55.1 0 0 1 375,167 Z"
                    />
                    <path
                      className="path-amras-5"
                      d="M 187,199 A 52,52 0 0 1 136,251 52,52 0 0 1 84.1,199 52,52 0 0 1 136,147 52,52 0 0 1 187,199 Z"
                    />
                    <path
                      className="path-amras-6"
                      d="M 287,217 A 66.8,66.8 0 0 1 221,284 66.8,66.8 0 0 1 154,217 66.8,66.8 0 0 1 221,150 66.8,66.8 0 0 1 287,217 Z"
                    />
                    <path
                      className="path-amras-7"
                      d="M 132,168 A 53.9,53.9 0 0 1 78.7,222 53.9,53.9 0 0 1 24.8,168 53.9,53.9 0 0 1 78.7,114 53.9,53.9 0 0 1 132,168 Z"
                    />
                    <path
                      className="path-amras-8"
                      d="M 343,211 A 48.7,48.7 0 0 1 295,260 48.7,48.7 0 0 1 246,211 48.7,48.7 0 0 1 295,163 48.7,48.7 0 0 1 343,211 Z"
                    />
                  </svg>
                  <div className="tooltip__content" id="info-amras">
                    <div>苏拉心相连、藏苏情深厚</div>
                    <div>携手共建数字化校园致词</div>
                    <div>殷飞 致</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )} */}
      </div>
      {/* {showModal && isFirstShow == 'first' && (
        <div className={styles.layer_wrapper} onClick={closeLayer}>
          <div className={styles.inner_Layer}>
            {sHowAnimal && (
              <div
                className={`${styles.contain_wrapper}`}
                onClick={preventCloseLayer}
              >
                <img src={schoolUrl} className={styles.envelopeUrl} />
                <img
                    src={closeUrl}
                    className={styles.closeIcon}
                    onClick={closeModal}
                  />
              </div>
            )}
          </div>
        </div>
      )} */}
    </>
  );
};

export default Home;
